const rootPath      = '../';
const currentPath   = './';

var config          = require(currentPath + 'config.js');
var common          = require(currentPath + 'common.js');
var Promise         = require(rootPath + 'util/promise.js');

// http request
function httpRequest(url, method, data)
{
    let header  = {
        "Content-Type" : "application/json",
    };

    if (common.isAuthorize()) {
        let token               = common.getAccessTokenSync();
        header.Authorization    = 'Bearer ' + token.token;
    }

    return new Promise((resolve, reject) => {
        wx.request({
            url     : url,
            method  : method,
            data    : data,
            header  : header,
            success : res => {
                // 如果登陆信息失效 将 sesssion 清除
                if (res.statusCode == 401) {
                    try {
                        wx.removeStorageSync(config.key.access_token_key);
                    } catch (e) {
                        console.log(e);
                    }
                }

                // 如果需要的话重新登录

                resolve(res);
            },
            fail : e => reject(e),
        });
    });
}

// http get
function httpGet(url, data = {})
{
    return httpRequest(url, 'GET', data);
}

// http post
function httpPost(url, data = {})
{
    return httpRequest(url, 'POST', data);
}

// 授权请求
function authorize(data)
{
    return httpPost(config.api.auth.login, data);
}

/*********************************** 产品 *************************************/
// 获取首页的列表
function getProducts(data)
{
    return httpGet(config.api.product.index, data);
}

// 获取一个商品
function getProduct(id)
{
    let url = config.api.product.show.replace(':id', id);

    return httpGet(url);
}

// 发布产品
function storeProduct(data)
{
    let url = config.api.product.store;

    return httpPost(url, data);
}

// 上传图片
function uploadImage(wxfile)
{
    let url     = config.api.image.store;
    let header  = {
        "Content-Type" : "application/json",
    };

    if (common.isAuthorize()) {
        let token               = common.getAccessTokenSync();
        header.Authorization    = 'Bearer ' + token.token;
    }

    return new Promise((resolve, reject) => {
        wx.uploadFile({
            url     : url,
            filePath: wxfile,
            header  : header,
            name    : config.key.upload_key,
            success : res => resolve(res),
            fail    : e => reject(e),
        });
    });
}

// 关注产品
function attentionProduct(id)
{
    let url = config.api.product.attention.replace(':id', id);

    return httpPost(url);
}

// 取消关注产品
function cancelAttentionProduct(id)
{
    let url = config.api.product.attention.replace(':id', id);

    return httpPost(url);
}

/*********************************** 评论 *************************************/
// 添加产品评论
function commentProduct(id, content)
{
    let url     = config.api.comment.store.replace(':id', id);
    let data    = {
        'content' : content,
    };

    return httpPost(url, data);
}

// 获取产品评论列表
function getCommentList(id, page)
{
    let url     = config.api.comment.list.replace(':id', id);
    let data    = {
        'page' : page,
    };

    return httpGet(url, data);
}

/*********************************** 竞价 *************************************/
// 获取某个产品的竞价列表
function getAuctionList(id, data)
{
    let url     = config.api.product.auction.replace(':id', id);

    return httpGet(url, data);
}

// 添加一条竞价记录
function postAuctionProduct(data)
{
    let url     = config.api.auction.store;

    return httpPost(url, data);
}

/*********************************** 订单 *************************************/
// 获取订单支付配置
function getPaymentConfig()
{
    let url = config.api.payment.config;

    return httpGet(url);
}

// 获取订单列表
function getOrderList(page)
{
    let url     = config.api.order.list;
    let data    = {
        'page' : page,
    };

    return httpGet(url, data);
}

// 通过id获取订单
function getOrderById(id)
{
    let url = config.api.order.get.replace(':id', id);

    return httpGet(url);
}

// 通过订单号获取订单
function getOrderBuNumber(number)
{
    let url = config.api.order.getnumber.replace(':number', number);

    return httpGet(url);
}

// 删除订单
function deleteOrderById(id)
{
    let url = config.api.order.delete.replace(':id', id);

    return httpPost(url);
}

// 删除订单
function deleteOrderByNumber(number)
{
    let url = config.api.order.deletenumber.replace(':number', number);

    return httpPost(url);
}

/*********************************** 微信 *************************************/
// 微信授权
function wechatLogin()
{
    return new Promise((resolve, reject) => {
        wx.login({
            success : response => {
                if (response.code) {
                    authorize({
                        code : response.code,
                    }).then(resp => {
                        let res     = resp.data.data;
                        let data    = {
                            'token'   : res.access_token,
                            'time'    : res.expires_time,
                        };

                        common.setAccessTokenSync(data);

                        resolve();
                    });
                } else {
                    reject(response);
                }
            },
            fail : e => reject(e),
        });
    });
}

// 发送微信用户的信息
function saveWechatUserInfo(info)
{
    let url     = config.api.auth.info;
    let data    = {
        'encryptData'   : info.encryptData,
        'encryptedData' : info.encryptedData,
        'rawData'       : info.rawData,
        'signature'     : info.signature,
        'userInfo'      : info.userInfo,
        'iv'            : info.iv,
    };

    return httpPost(url, data);
}

// 更新用户的微信信息
function getUserInfo()
{
    return new Promise((resolve, reject) => {
        wx.getUserInfo({
            success : res => resolve(res),
            fail : e => reject(e),
        });
    });
}

exports = module.exports = {
    authorize           : authorize,
    wechatLogin         : wechatLogin,
    getUserInfo         : getUserInfo,
    saveWechatUserInfo  : saveWechatUserInfo,

    uploadImage         : uploadImage,

    getProducts         : getProducts,
    getProduct          : getProduct,
    storeProduct        : storeProduct,
    attentionProduct    : attentionProduct,
    postAuctionProduct  : postAuctionProduct,
    getAuctionList      : getAuctionList,
};
